<template>
  <!-- 顶部 -->
  <van-nav-bar left-arrow title="购物车" @click-left="onClickLeft" />
  <!-- 商品列表 -->
  <div class="car-list" v-if="hasCartData">
    <!-- 商品 -->
    <cart-item
    v-for="item in cartList" :key="item.id" :cartData="item">
    </cart-item>
    <!-- 总计 -->
    <van-submit-bar :price="store.getters['car/totalPrice'] * 100" button-text="去结算"
    @submit="handleClick">
      <van-checkbox v-model="checkedAll" checked-color="#ee0a24">全选</van-checkbox>
    </van-submit-bar>
  </div>
  <!-- 没有商品列表 -->
  <van-empty v-else description="暂时没有宝贝哦~" />
  <!-- 底部公共区域 -->
  <layout-footer></layout-footer>
</template>
<script setup>
import { NavBar as VanNavBar, SubmitBar as VanSubmitBar, 
Checkbox as VanCheckbox, Empty as VanEmpty } from 'vant'
import CartItem from './components/cartItem.vue'
import { getCartList } from '@/api/cart.js'
import layoutFooter from '@/components/layoutFooter.vue'
import { nextTick, ref } from 'vue'
import { computed } from '@vue/reactivity'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
const store = useStore()
const router = useRouter()

// ---- 列表数据处理  -----
// 存储购物车数据
const cartList = computed(() => store.state.car.carlist)
// 判断商品列表是否为空
const hasCartData =computed(() => cartList.value.length !== 0 )
// 初始化购物车数据
const initCartList = async () => {
const { data } = await getCartList({
  // page：页数 limit：每页个数
  page: 1,
  limit: 10 
})
if (data.status !== 200){ return }
// console.log(data)
// 在请求数据之后 遍历存储数据之前 将数据先清除
store.commit('car/clear')
// 处理渲染异常 同步操作 先请求数据清除数据 再遍历存储数据
await nextTick()
data.data.valid.forEach(item => {
  store.commit('car/addToCart', {
    id: item.id,
    count: item.cart_num,
    checked: true,
    image: item.productInfo.image,
    title: item.productInfo.store_name,
    price: item.truePrice,
    stock: item.trueStock,
    productId:item.product_id
  })
  
});
}  
initCartList()


// 顶部返回按钮
const onClickLeft = () =>{
  router.push({
    name: 'home' 
  })
}


// ----全选处理 -----
const checkedAll = computed({
  get: () => store.getters['car/checkedAll'],
  set (newStatus){
    store.commit('car/changeAll', { checked: newStatus })
  }
})


// ---- 去结算处理 -----
const handleClick = () => {
  // let carId = store.getters['car/checkedItems'].map(item => item.id).toString()
  // console.log(carId)
    router.push({
      name: 'order-confirm',
      query: {
        // carId 是指 要结算的sku的id集合，以逗号链接后传递
        carId: store.getters['car/checkedItems'].map(item => item.id).toString()
      }
  })
}

</script>
<style lang='scss' scoped>
// 顶部
.van-nav-bar{
  position: fixed !important;
  top: 0;
  width: 100%;
}
// 商品列表
.car-list{
  // 流出顶部及底部导航和总计区域
  margin: 50px 0 100px;
  background-color: rgb(241, 240, 240);
}
// 总计区域
.van-submit-bar{
  margin-bottom: 50px;
}
</style>